var routesApp = angular.module("routesApp", ["ui.bootstrap","ngRoute"]);
//contextPath: Se obtiene desde el controlador y sirve para determinar la url actual

routesApp    
    .factory('routes', dataFactory)
    .factory('utils',utilsFactory)
    .factory('gridConfig',gridConfigFactory)
    .service('modalService',modalService)
    .directive('ngJqgrid', ngJqgrid)
    .directive('angucomplete',angucomplete)
    .config(function ($routeProvider, $locationProvider) {
        $locationProvider.hashPrefix('!');
        $routeProvider
            .when('/index',
                {
                    controller: 'indexController',
                    templateUrl: 'index.html'
                })        
            .when('/edit/:id',
                {
                    controller: 'editRouteController',
                    templateUrl: 'edit.html'
                })
            .when('/add',
                {
                    controller: 'editRouteController',
                    templateUrl: 'edit.html'
                })
            .when('/edit/:id/points',
                {
                    controller: 'routePoinController',
                    templateUrl: 'indexRoutePoint.html'
                })
            .otherwise({ redirectTo: '/index' });
    })
    .run(function($rootScope,routes){
        
        $rootScope.points = [];
        routes.getData(contextPathPoints + "getPointByName", {})
            .success(function(data, status, headers, config) {
               $rootScope.points = data[0];
            })
            .error(function(data, status, headers, config) {
                console.log('Error');
            });
            
       $rootScope.pointStatus = [
           {id:0, status:'Sin estatus'},
           {id:1, status:'Normal'},
           {id:2, status:'Pausado'},
           {id:3, status:'Cancelado'}
       ];
       
        $rootScope.pointAvailability = [
           {id:1, tipo:'Obligatorio'},
           {id:0, tipo:'No obligatorio'}
       ];
    });


routesApp.controller("indexController", function($rootScope,$scope, $location, routes, modalService, gridConfig) {
    $scope.init = function(){
        $(window).on('resize', function(event, ui) {
            var parWidth = $("#gbox_grdRoutes").parent().parent().parent().width();
            var curWidth = $("#gbox_grdRoutes").width();
            var w = parWidth - 1;
            if (Math.abs(w - curWidth) > 2)
            {  
                $("#grdRoutes").setGridWidth(w);
            }
        }).trigger('resize');
    }
    $scope.grid = {};
    
    $scope.refresh = function(){
        $scope.grid.api.refresh();
    }
    
    $scope.goEdit = function(path){
        if($scope.routeId)
           $scope.go(path); 
        else{
            var modalOptions = {
                actionButtonText: 'Aceptar',
                bodyText: 'Para poder editar, es necesario seleccionar primero un registro.'
            };
            modalService.showModal({templateUrl: 'modalInfo.html'}, modalOptions);
        }
    }
    
    $scope.go = function ( path ) {
        $location.path( path );
    };
    
    $scope.alerts = [];
    $scope.closeAlert = function(index) {
        $scope.alerts.splice(index, 1);
    };
  
    $scope.delete = function(id){
        if (id) {
            var modalOptions = {
                closeButtonText: 'Cancelar',
                actionButtonText: 'Eliminar',
                bodyText: '¿Estás seguro de eliminar esta Ruta?'
            };
            modalService.showModal({}, modalOptions).then(function (result) {
                $scope.loading = true;
                routes.delete(contextPath + "delete", {id: id})
                .success(function(data, status, headers, config) {
                    $scope.loading = false;
                    if(data.error){
                        var modalOptions = {
                            actionButtonText: 'Aceptar',
                            bodyText: data.error
                        };
                        modalService.showModal({templateUrl: 'modalInfo.html'}, modalOptions);
                    }else{
                        var modalOptions = {
                            actionButtonText: 'Aceptar',
                            bodyText: '¡Registro eliminado con éxito!'
                        };
                        modalService.showModal({templateUrl: 'modalInfo.html'}, modalOptions).then(function (result){
                             $scope.grid.api.refresh();
                        });
                    }                   
                    })
                .error(function(data, status, headers, config) {
                    $scope.loading = false;
                    var modalOptions = {
                            actionButtonText: 'Aceptar',
                            bodyText: 'Ocurrió un error al eliminar el registro.'
                        };
                        modalService.showModal({templateUrl: 'modalInfo.html'}, modalOptions);
                });
            });
        }else{
            var modalOptions = {
                actionButtonText: 'Aceptar',
                bodyText: 'Para poder eliminar, es necesario seleccionar primero un registro.'
            };
            modalService.showModal({templateUrl: 'modalInfo.html'}, modalOptions);
        }
    }
    
    
    $scope.grid.config = gridConfig.config({
	url: contextPath + "getRoutes",
        //datatype:'local',
	colNames: ["id", "Clave", "Nombre", "Estatus", "Capacidad", "Factor", "Estado"],
	colModel: [
		{name: "id", width: 0, align: "right", hidden: true},
		{name: "code", index: "code", width: 80},
		{name: "name", index: "name", width: 150},
		{name: "estatus", index: "estatus", width: 50},
		{name: "capacity", index: "capacity", width: 50},
                {name: "factor", index: "factor", width: 50, formatter: 'number', formatoptions: {decimalPlaces: 0, separator:",", suffix: ""}},
                {name: "estado", index: "estado", width: 80}                
	],
	sortname: "name",
	sortorder: "asc",
	caption: "Rutas",
        onSelectRow: function(id){
            $scope.$apply(function(){
                $scope.selRow = id;
                $scope.routeId = $scope.grid.apicall('getRowData', id).id
            });
        },
        beforeRequest: function(){
        },
        loadComplete: function (data) {
            $scope.$apply(function(){
                $rootScope.data = data; 
                $scope.selRow =null;
                $scope.routeId = null;
            });
            $scope.init();
        }
    },{id:"id"});
});

routesApp.controller("editRouteController", function($rootScope,$scope, $location, $routeParams, routes, utils, modalService, gridConfig) {
    $scope.sc = {loading:false}
    $scope.go = function ( path ) {
        $location.path( path );
    };
    
    init();
    
    function init() {
        //Catálogos Iniciales
        $scope.routeStatus = [{id:0, status:'Inactiva'},{id:1, status:'Activa'}]
       
        //Asignaciones iniciales
        $scope.route = {}
        setSelectedRouteStatus(1);        
       
        var routeId = ($routeParams.id) ? parseInt($routeParams.id) : 0;
        if (routeId > 0) {
            if($scope.data){
                $scope.route = utils.findById($scope.data[0],'id',routeId)
                if(!$scope.route){
                    $scope.go("/index");
                     return;
                }
                $rootScope.route = $scope.route;
                setSelectedRouteStatus($scope.route.status);
            }else{
                $scope.sc.loading = true;
                routes.getData(contextPath + "getRoutes", {page: 1, rowsPerPage: 1, sortField: 'name', sortDir: 'asc', id: routeId})
                    .success(function(data, status, headers, config) {
                        $scope.sc.loading = false;
                        if(!data[0][0]){
                            $scope.go("/index");
                            return;
                        }
                        $scope.route = data[0][0];
                        $rootScope.route = $scope.route;
                        setSelectedRouteStatus($scope.route.status);
                    })
                    .error(function(data, status, headers, config) {
                        alert('Error');
                    });
            }
            
            
        }
    }
    
    $scope.save = function(){
        if($scope.route){
            $scope.sc.loading=true;
            routes.save(contextPath + "save", $scope.route, {})
                .success(function(data, status, headers, config){
                    $scope.sc.loading=false;
                    if (data.error) {
                         var modalOptions = {
                            actionButtonText: 'Aceptar',
                            bodyText: data.error
                        };
                        modalService.showModal({templateUrl: 'modalInfo.html'}, modalOptions);
                    } else {
                        var modalOptions = {
                            actionButtonText: 'Aceptar',
                            bodyText: '¡Registro guardado con éxito!'
                        };
                        modalService.showModal({templateUrl: 'modalInfo.html'}, modalOptions).then(function (result) {
                                $location.path('/index');
                            });
                        }
                })
                .error(function(data, status, headers, config){
                    $scope.sc.loading = false;
                    alert('Error');
                });
        }
    }
    
    function setSelectedRouteStatus(value){
        for(var i=0;i<$scope.routeStatus.length;i++){
            if($scope.routeStatus[i]["id"]==value){
                $scope.route.status = $scope.routeStatus[i]["id"];
                return;
            }
        }
    }
    
    $scope.getFormFieldCssClass = function(ngModelController) {
        if(ngModelController.$pristine) return "";
        return ngModelController.$valid ? "has-success" : "has-error";
    }
    
    
});

routesApp.controller("routePoinController", function($rootScope,$scope, $route,$location, $routeParams, routes, utils, modalService, gridConfig, $compile, $timeout){
    $scope.grid = {edit: {selectedPoint: {id:null, point:null, pointType:null}, originalObject:{}}};
    $scope.grid.edit.lastSel = null;
    $scope.grid.edit.selRow = null;
    $scope.routeSummary = {};    
    
    /* Alerts */
    $scope.routeAlerts = [];
    $scope.closeAlert = function(index) {
        $scope.routeAlerts.splice(index, 1);
    };
    /* Alerts */
    
    $(window).on('resize', function(event, ui) {
        resizeGrid();
    }).trigger('resize');
    
    function resizeGrid(){
        var parWidth = $("#gbox_grdRoutePoints").parent().parent().width();
        var curWidth = $("#gbox_grdRoutePoints").width();
        var w = parWidth - 1;        
        if (Math.abs(w - curWidth) > 2)
        {  
            $("#grdRoutePoints").setGridWidth(w);
        }
    }
    init();
    $scope.go = function ( path ) {
        $location.path( path );
    };
    function init(){       
        //Catálogos Iniciales
        var routeId = ($routeParams.id) ? parseInt($routeParams.id) : 0;
        if (parseInt(routeId) > 0) {
            if(!$scope.route){    
                routes.getData(contextPath + "getRoutes", {page: 1, rowsPerPage: 1, sortField: 'name', sortDir: 'asc', id: routeId})
                    .success(function(data, status, headers, config) {
                        if(!data[0][0]){
                            $scope.go("/index");
                            return;
                        }
                        $scope.route = data[0][0];
                        if($scope.route.close == 1)
                            $scope.routeAlerts.push({msg: 'La ruta se encuentra cerrada, para poder agregar nuevos puntos, editar o eliminar los puntos existentes o cambiar el orden de estos, es necesario abrir la ruta.', type:'info'});
                        else
                            $scope.routeAlerts.push({msg: 'La ruta se encuentra abierta, para poder programar una ruta es necesario que la ruta se encuentre cerrada. \n\ Una ruta solo puede ser cerrada agregando un centro de intercambio como punto final de la ruta.', type:'info'});
                    })
                    .error(function(data, status, headers, config) {
                        alert('Error');
                    });
            }else{
                if($scope.route.close == 1)
                    $scope.routeAlerts.push({msg: 'La ruta se encuentra cerrada, para poder agregar nuevos puntos, editar o eliminar los puntos existentes o cambiar el orden de estos, es necesario abrir la ruta.', type:'info'});
                else
                    $scope.routeAlerts.push({msg: 'La ruta se encuentra abierta, para poder programar una ruta es necesario que la ruta se encuentre cerrada. \n\ Una ruta solo puede ser cerrada agregando un centro de intercambio como punto final de la ruta.', type:'info'});
            }
        }
    
       resizeGrid();       
    }
    
    $scope.setLoading = function(value){
        $scope.sc.loading = value;
    }    
    $scope.sc = {loading:false};
    
    $scope.openRoute = function(){
        $scope.sc.loading = true;
        routes.save(contextPath + "routeToggleOpenClose", {id: $scope.route.id, close:0})
                .success(function(data, status, headers, config) {
                    $scope.sc.loading = false;
                    if(data.error){
                        var modalOptions = {actionButtonText: 'Aceptar', bodyText: data.error, };
                        modalService.showModal({templateUrl: 'modalInfo.html'}, modalOptions);
                    }else{
                        var modalOptions = {actionButtonText: 'Aceptar', bodyText: 'La ruta se abrió correctamente.'};
                        modalService.showModal({templateUrl: 'modalInfo.html'}, modalOptions).then(function (result) {
                            var currentRoute = data[0][0];
                            //Actualizar la ruta en el rootScope
                            $rootScope.route = currentRoute;
                            //Actualizar la lista de rutas  en el rootScope, si se ha entrado directamente, $scope.data no existirá                            
                            if($scope.data){
                                for(var i=0;i<=$scope.data[0].length;i++){
                                    if($scope.data[0][i].id == currentRoute.id){                                    
                                        $scope.data[0][i] = currentRoute;
                                        break;
                                    }
                                }
                            }
                            $route.reload();
                        });
                        
                    }
                    })
                .error(function(data, status, headers, config) {
                    $scope.sc.loading = false;
                    var modalOptions = {actionButtonText: 'Aceptar', bodyText: 'Ocurrió un error al abrir la ruta.'};
                    modalService.showModal({templateUrl: 'modalInfo.html'}, modalOptions);
                });
    }
    
    $scope.closeRoute = function(){
        $scope.sc.loading = true;        
        routes.save(contextPath + "routeToggleOpenClose", {id: $scope.route.id, close:1})
                .success(function(data, status, headers, config) {
                    $scope.sc.loading = false;
                    if(data.error){
                        var modalOptions = {actionButtonText: 'Aceptar', bodyText: data.error, };
                        modalService.showModal({templateUrl: 'modalInfo.html'}, modalOptions);
                    }else{
                        var modalOptions = {actionButtonText: 'Aceptar', bodyText: 'La ruta se cerró correctamente.'};
                        modalService.showModal({templateUrl: 'modalInfo.html'}, modalOptions).then(function (result) {
                            var currentRoute = data[0][0];
                            //Actualizar la ruta en el rootScope
                            $rootScope.route = currentRoute;
                            //Actualizar la lista de rutas  en el rootScope, si se ha entrado directamente, $scope.data no existirá                            
                            if($scope.data){
                                for(var i=0;i<=$scope.data[0].length;i++){
                                    if($scope.data[0][i].id == currentRoute.id){                                    
                                        $scope.data[0][i] = currentRoute;
                                        break;
                                    }
                                }
                            }
                            $route.reload();
                        });
                        
                    }
                    })
                .error(function(data, status, headers, config) {
                    $scope.sc.loading = false;
                    var modalOptions = {actionButtonText: 'Aceptar', bodyText: 'Ocurrió un error al cerrar la ruta.'};
                    modalService.showModal({templateUrl: 'modalInfo.html'}, modalOptions);
                });
    }
    
    $scope.routePointChangeOrder = function(pointId, dir){
        $scope.sc.loading = true;
        routes.save(contextPath + "routePointChangeOrder", {id: pointId, dir:dir})
                .success(function(data, status, headers, config) {
                    $scope.sc.loading = false;
                    if(data.error){
                        var modalOptions = {actionButtonText: 'Aceptar', bodyText: data.error, };
                        modalService.showModal({templateUrl: 'modalInfo.html'}, modalOptions);
                    }else{
                        $scope.grid.api.refresh();
                    }
                    })
                .error(function(data, status, headers, config) {
                    $scope.sc.loading = false;
                    var modalOptions = {actionButtonText: 'Aceptar', bodyText: 'Ocurrió un error al actualizar el registro.'};
                    modalService.showModal({templateUrl: 'modalInfo.html'}, modalOptions);
                });
    }
    
    $scope.delete = function(id){
        if (id) {
            var modalOptions = {closeButtonText: 'Cancelar', actionButtonText: 'Eliminar', bodyText: '¿Estás seguro de eliminar este punto de venta?'};
            modalService.showModal({}, modalOptions).then(function (result) {
                $scope.sc.loading = true;
                routes.delete(contextPath + "routePointDelete", {id: id})
                .success(function(data, status, headers, config) {
                    $scope.sc.loading = false;
                    if(data.error){
                        var modalOptions = {actionButtonText: 'Aceptar', bodyText: data.error, };
                        modalService.showModal({templateUrl: 'modalInfo.html'}, modalOptions);
                    }else{
                        var modalOptions = {actionButtonText: 'Aceptar', bodyText: '¡Registro eliminado con éxito!'};
                        modalService.showModal({templateUrl: 'modalInfo.html'}, modalOptions).then(function (result){
                        $scope.grid.api.refresh();
                        });
                    }
                    })
                .error(function(data, status, headers, config) {
                    $scope.sc.loading = false;
                    var modalOptions = {actionButtonText: 'Aceptar', bodyText: 'Ocurrió un error al eliminar el registro.'};
                    modalService.showModal({templateUrl: 'modalInfo.html'}, modalOptions);
                });
            });
        }else{
            var modalOptions = {actionButtonText: 'Aceptar', bodyText: 'Para poder eliminar, es necesario seleccionar primero un registro.'};
            modalService.showModal({templateUrl: 'modalInfo.html'}, modalOptions);
        }
    }
    
    $scope.accordion = {status:{open: true}};
    
    $scope.grid.config = gridConfig.config({
	url: contextPath + "getRoutePoints",
	colNames: ["id","route_id","Punto de venta", "Orden","Tipo", "Tiempo","Estatus","Requerido"],
	colModel: [
		{name: "id", index:"id", width: 0, align: "right", editable: false, hidden: true},
                {name: "route_id", index:"route_id", width: 0, align: "right", editable: true, hidden: true},                
		{name: "point_id", index: "point_id", width: 180, editable: true, sortable:false, edittype: "custom",
                    formatter: formatterPoint,
                    unformat: unformatPoint,
                    editoptions: {
                        custom_element: getPointSearcher,
                        custom_value: customCboValue
                    }
                },
                {name: "order_number", index:"order_number", width: 0, align: "right", editable: false, hidden: true},
		{name: "tipo", index: "tipo", width: 100, editable: false, sortable:false},                
                {name: "arrival_time", index: "arrival_time", width: 50, editable: true, sortable:false},
                {name: "status", index: "status", width: 100, editable: true, sortable:false, edittype: "custom",
                    formatter: formatterPointStatus,
                    unformat: unformatPointStatus,
                    editoptions: {
                        custom_element: getPointStatus,
                        custom_value: customPointStatusValue
                    }
                },
                {name: "required", index: "required", width: 100, editable: true, sortable:false, edittype: "custom",
                    formatter: formatterPointAvailability,
                    unformat: unformatPointAvailability,
                    editoptions: {
                        custom_element: getPointAvailability,
                        custom_value: customPointAvailabilityValue
                    }
                }
                
	],
        width:'700',
        rowNum: 15,
        rowList: [15, 30, 45],
	sortname: "name",
	sortorder: "asc",
	caption: "Puntos de venta",
        editurl: contextPath + "routePointSave",
        serializeRowData: function (postdata) {            
            console.log($scope.grid.edit.selectedPoint.point,$scope.grid.edit.selectedPoint.pointType)
            
            $scope.sc.loading = true;            
            $scope.textSearchStr = '';
            var currentRow = $scope.grid.apicall('getRowData', $scope.grid.edit.selRow);           
            if(currentRow){                
                if(parseInt(currentRow.id)){ 
                    postdata.id = currentRow.id;
                }else{
                    delete postdata.id
                }
                postdata.order_number = currentRow.order_number;
                if($scope.grid.edit.closeRoute) postdata.actionClose = "S"
            }
            postdata.route_id = $routeParams.id;
            return JSON.stringify(postdata);
            },
        onSelectRow: function(id){
            if(id && id!==$scope.grid.edit.lastSel){ 
                $scope.grid.edit.cancel();
                $scope.grid.edit.lastSel=id; 
            }
            //Se aplica timeout en vez de $scope.apply debido a que en este punto, la funcion apply del scope está en progreso
            //De esta manera la función se agrega a la cola de procesos, por tanto, se ejecuta al último.
            $timeout(function() {
                $scope.grid.edit.selRow = id;
                $scope.grid.edit.routePointId = $scope.grid.apicall('getRowData', id).id
            },0);
        },
        beforeProcessing: function(data, status, xhr){
            $scope.sc.loading = false;
            if(data.error){                
            }
        },
        beforeRequest: function(){
            $scope.sc.loading = true;
        },
        loadComplete: function (data) {
            $timeout(function(){
                $scope.routeSummary = data[2][0]; 
                $scope.grid.edit.selRow =null;
                $scope.grid.edit.routePointId = null;
            },0);
            resizeGrid();
        },
        serializeGridData: function(postData) {
            postData.route_id = $routeParams.id;
            return JSON.stringify(postData);
        }
    },{});
    
    // *** --------------------------- Grid button bar --------------------------- ***
    $scope.grid.edit.delRow = function(){
        var currentRow = $scope.grid.apicall('getRowData', $scope.grid.edit.selRow);
        if(currentRow){
            if(parseInt(currentRow.id)){ 
                $scope.delete(parseInt(currentRow.id));
            }
        } 
    }
    
    $scope.grid.edit.refresh = function(){
        $scope.grid.api.refresh();
    }
    
    $scope.grid.edit.addRow = function(){
        $scope.grid.apicall('addRow',0,{
            afterrestorefunc: function () {
                     $scope.grid.edit.selectedPoint = {id: null, point: null, pointType:null}
                }
        });
        $scope.grid.edit.isEditing = true;
    }
    
    $scope.grid.edit.cancel = function(){
        $scope.grid.apicall('restoreRow',$scope.grid.edit.selRow);
        $scope.grid.edit.isEditing = false;
        var selRow = $scope.grid.edit.selRow;
        if(selRow && selRow.indexOf("jqg")>=0)
            $scope.grid.edit.selRow = null;        
        $scope.grid.edit.selectedPoint = {id: null, point: null, pointType:null}
    }
    
    $scope.grid.edit.editRow = function(){
        $scope.grid.edit.isEditing = true;
        if($scope.grid.edit.selRow){
            $scope.grid.apicall('editRow',$scope.grid.edit.selRow,{
                afterrestorefunc: function () {
                     $scope.grid.edit.selectedPoint = {id: null, point: null, pointType:null}
                }
            });
        }else{}
    }
    
    $scope.grid.edit.saveRow = function(){
        $scope.sc.loading = true;    
        if($scope.grid.edit.selRow){        
            $scope.grid.apicall('saveRow',$scope.grid.edit.selRow,{
                successfunc: function (response) {
                        $scope.sc.loading = false;
                        var data = eval('(' + response.responseText + ')');
                        if (data.error) {
                            var modalOptions = {actionButtonText: 'Aceptar', bodyText: data.error};
                            modalService.showModal({templateUrl: 'modalInfo.html'}, modalOptions);
                        } else {
                            var modalOptions = {actionButtonText: 'Aceptar', bodyText: '¡Registro guardado con éxito!'};
                            modalService.showModal({templateUrl: 'modalInfo.html'}, modalOptions).then(function(result) {
                                $scope.grid.api.refresh();
                            });
                        }    
                    },
                restoreAfterError: true,
                errorfunc: function (rowid, response) {
                    $scope.sc.loading = false;
                    if(response.statusText!=="OK"){
                        var modalOptions = {actionButtonText: 'Aceptar', bodyText: "Ocurrió un error al guardar el registro"};
                        modalService.showModal({templateUrl: 'modalInfo.html'}, modalOptions);
                    }
                },
                afterrestorefunc: function () {
                     $scope.sc.loading = false;
                     $scope.grid.edit.selectedPoint = {id: null, point: null, pointType:null}
                     $scope.grid.edit.selRow = false;
                }
                }
            );
            
            $scope.grid.edit.isEditing = false;
        }else{}
    }
    
    $scope.grid.edit.upRow = function(){
        var currentRow = $scope.grid.apicall('getRowData', $scope.grid.edit.selRow);
        if (currentRow.id){            
            var modalOptions = {closeButtonText: 'Cancelar', actionButtonText: 'Subit ruta', bodyText: '¿Estás seguro de subir la ruta actual?'};
            modalService.showModal({}, modalOptions).then(function (result) {
                $scope.sc.loading = true;
                $scope.routePointChangeOrder(currentRow.id,"UP");
            });
        }else {}
    }
    
    $scope.grid.edit.downRow = function(){
        var currentRow = $scope.grid.apicall('getRowData', $scope.grid.edit.selRow);                
        if (currentRow.id) {           
            var modalOptions = {closeButtonText: 'Cancelar', actionButtonText: 'Bajar ruta', bodyText: '¿Estás seguro de bajar la ruta actual?'};
            modalService.showModal({}, modalOptions).then(function (result) {
                $scope.sc.loading = true;
                $scope.routePointChangeOrder(currentRow.id,"DOWN");
            });
        }else {}
    }
    
    //*** --------------------------- Grid button bar --------------------------- ***
    //
    // *** --------------------------- Grid combo Helpers --------------------------- ***
    // *** ----------------- Combo Punto de venta ----------------- ***  
    
    function getPointSearcher(value, options){
        $scope.textSearchStr = '';
        if(value>=0){
            for (var i = 0; i < $scope.points.length; i++)
                if (parseInt($scope.points[i].id) == parseInt(value)) {
                    $scope.textSearchStr = $scope.points[i].point;                    
                    $scope.grid.edit.selectedPoint.id = $scope.points[i].id;
                    $scope.grid.edit.selectedPoint.pointType = $scope.points[i].type;
                    break;
                }
        }
        
        var pointSearchMarkup = '<angucomplete id="ptos" \n\
                                    placeholder="Buscar puntos de venta" \n\
                                    pause="100" \n\
                                    selectedobject="grid.edit.selectedPoint" \n\
                                    localdata="points" \n\
                                    searchfields="point" \n\
                                    titlefield="point" \n\
                                    inputclass="form-control" \n\
                                    matchclass="highlight"/>';
        
        var pointSearcher =   angular.element(pointSearchMarkup);
        var compiledPointSearcher = $compile(pointSearcher)($scope);        
        return compiledPointSearcher;
    }    
    
    $scope.textSearchStr = '';
    function customCboValue(elem, operation, value) { 
        console.log("combo value")
        if (operation === 'get') {
            //Si no seleccionaron un elemento de la lista el objeto originalObject no existirá, entonces se tomará el id de la ruta actual
            if($scope.grid.edit.selectedPoint){
                if(!$scope.grid.edit.selectedPoint.originalObject)
                    return $scope.grid.edit.selectedPoint.id
                else{
                    $scope.grid.edit.selectedPoint.pointType = $scope.grid.edit.selectedPoint.originalObject.type;
                    return $scope.grid.edit.selectedPoint.originalObject.id;
                }
            }else{return null};
        } else if (operation === 'set') {
            console.log('set')
        }
    }
    
    function formatterPoint(cellvalue, options, rowObject, action) {        
        if (cellvalue > 0)
            for (var i = 0; i < $scope.points.length; i++)
                if ($scope.points[i].id == cellvalue) {
                    return $scope.points[i].point;
                }
    }
    
    function unformatPoint(cellvalue, options, cell) {
        if (cellvalue)
            for (var i = 0; i < $scope.points.length; i++)
                if ($scope.points[i].point === cellvalue){
                    $scope.grid.edit.selectedPoint.id = $scope.points[i].id;
                    return $scope.points[i].id;
                }
    }    
    
     // *** ----------------- Combo Punto de venta ----------------- ***
     
     // *** ----------------- Combo Status ----------------- ***
    function setSelectedPointStatus(value){
        for(var i=0;i<$scope.pointStatus.length;i++){
            if($scope.pointStatus[i]["id"]==value){
                $scope.grid.edit.pointStatus = $scope.pointStatus[i]["id"];
                return;
            }
        }
    }
    
    setSelectedPointStatus(1);
    function getPointStatus(value, options){
        if(value>=0){
            for (var i = 0; i < $scope.pointStatus.length; i++)
                if ($scope.pointStatus[i].id == parseInt(value)) {
                    setSelectedPointStatus(value);
                    break;
                }
        }
        var markup = '<select id="pointStatus" name="pointStatus" class="form-control" ng-model="grid.edit.pointStatus" \n\
                        ng-options="opt.id as opt.status for opt in pointStatus"> \n\
                      </select>';
        var pointStatus = angular.element(markup);
        var compiledPointStatus = $compile(pointStatus)($scope);        
        return compiledPointStatus;
    }
    
    function formatterPointStatus(cellvalue, options, rowObject, action) {        
        if (cellvalue>=0)
            for (var i = 0; i < $scope.pointStatus.length; i++)
                if ($scope.pointStatus[i].id == cellvalue) {
                    return $scope.pointStatus[i].status;
                }
    }
    
    function unformatPointStatus(cellvalue, options, cell) {
        if (cellvalue)
            for (var i = 0; i < $scope.pointStatus.length; i++)
                if ($scope.pointStatus[i].status === cellvalue){
                    return $scope.pointStatus[i].id;
                }
    }
    
    function customPointStatusValue(elem, operation, value) {       
        if (operation === 'get') {
            return $scope.grid.edit.pointStatus;
        } else if (operation === 'set') {
            console.log('set')
        }
    }
    // *** ----------------- Combo status ----------------- ***
    
    // *** ----------------- Combo requerido ----------------- ***
    function setSelectedPointAvailability(value){
        for(var i=0;i<$scope.pointAvailability.length;i++){
            if($scope.pointAvailability[i]["id"]==value){
                $scope.grid.edit.pointAvailability = $scope.pointAvailability[i]["id"];
                return;
            }
        }
    }
    
    setSelectedPointAvailability(1);
    function getPointAvailability(value, options){
        if(value>=0){
            for (var i = 0; i < $scope.pointAvailability.length; i++)
                if (parseInt($scope.pointAvailability[i].id) == parseInt(value)) {
                    setSelectedPointAvailability(parseInt(value));
                    break;
                }
        }
        var markup = '<select id="pointAvailability" name="pointAvailability" class="form-control" ng-model="grid.edit.pointAvailability" \n\
                        ng-options="opt.id as opt.tipo for opt in pointAvailability"> \n\
                      </select>';
        var pointAvailability = angular.element(markup);
        var compiledPointAvailability = $compile(pointAvailability)($scope);        
        return compiledPointAvailability;
    }
    
    function formatterPointAvailability(cellvalue, options, rowObject, action) {        
        if (cellvalue>=0)
            for (var i = 0; i < $scope.pointAvailability.length; i++)
                if ($scope.pointAvailability[i].id == cellvalue) {
                    return $scope.pointAvailability[i].tipo;
                }
    }
    
    function unformatPointAvailability(cellvalue, options, cell) {
        if (cellvalue)
            for (var i = 0; i < $scope.pointAvailability.length; i++)
                if ($scope.pointAvailability[i].tipo === cellvalue){
                    return $scope.pointAvailability[i].id;
                }
    }
    
    function customPointAvailabilityValue(elem, operation, value) {       
        if (operation === 'get') {
            return $scope.grid.edit.pointAvailability;
        } else if (operation === 'set') {
            console.log('set')
        }
    }
    // *** ----------------- Combo requerido ----------------- ***
    
    // *** --------------------------- Grid combo Helpers --------------------------- ***   
    
});
